import { joinTime, joinUser, transformUser } from './helper'
import { convertMinutesToHoursAndMinutes } from './MixinShiftUnitLists'
import { uuid } from '@/utils'
import { PAGE_SIZES } from '@/constant/modules/paging'
import ScheduleSchemeShift from '@/components/ScheduleSchemeShift/ScheduleSchemeShift.vue'
import ScheduleSchemeTeam from '@/components/ScheduleSchemeTeam/ScheduleSchemeTeam.vue'
import type { ScheduleScheme, TableColumn } from '@/types'

import { schedulingApi } from '@/api'

function getScheduleSchemeLists(params: {
  pageNumber: number
  pageSize: number
}) {
  const { pageNumber = 1, pageSize = 10 } = params || {}
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        ...Array(pageSize)
          .fill(1)
          .map((_v, i) => {
            const id = (pageNumber - 1) * pageSize + i + 1
            const c = Math.round(Math.random())
            return {
              id,
              name: `排班方案名称${id}`,
              shiftUnit: {
                id,
                name: `班次单元名称${id}`,
              },
              shift: c
                ? [
                    {
                      id: id + 1,
                      name: '早班',
                      time: '06:00-14:00',
                      duration: 8 * 60,
                      isCrossDay: 0,
                    },
                    {
                      id: id + 2,
                      name: '晚班',
                      time: '14:00-22:00',
                      duration: 8 * 60,
                      isCrossDay: 0,
                    },
                    {
                      id: id + 3,
                      name: '通班',
                      time: '22:00-06:00',
                      duration: 8 * 60,
                      isCrossDay: 1,
                    },
                  ]
                : [
                    {
                      id: id + 1,
                      name: '早班',
                      time: '00:00-08:00',
                      duration: 8 * 60,
                      isCrossDay: 0,
                    },
                    {
                      id: id + 2,
                      name: '中班',
                      time: '08:00-16:00',
                      duration: 8 * 60,
                      isCrossDay: 0,
                    },
                    {
                      id: id + 3,
                      name: '晚班',
                      time: '16:00-00:00',
                      duration: 8 * 60,
                      isCrossDay: 0,
                    },
                  ],
              team: [
                { id: id + 1, name: '班组名称甲' },
                { id: id + 2, name: '班组名称乙' },
                { id: id + 3, name: '班组名称丙' },
                { id: id + 4, name: '班组名称丁' },
                { id: id + 5, name: '班组名称戊' },
              ],
              creationTime: randTime(),
              creatorUserId: 10,
              creatorUserName: '张飞',
              creatorLoginName: 'zhangfei',
              updateTime: randTime(),
              updateUserId: 10,
              updatorUserName: '张飞',
              updatorLoginName: 'zhangfei',
            }
          }),
      ])
    }, 600)
  })
}

function transfer(data: {
  schedulingScheme: any
  shiftUnit: any
  shiftList: any[]
  teamList: any
}[]): ScheduleScheme[] {
  return data.map(v => ({
    id: v.schedulingScheme.id,
    name: v.schedulingScheme.name,
    shiftUnit: {
      id: v.shiftUnit.id,
      name: v.shiftUnit.name,
    },
    shift: (v.shiftList || []).map(vv => ({
      id: vv.id,
      name: vv.name,
      time: joinTime(vv.startTime, vv.endTime),
      duration: vv.totalTimeMinute,
      durationString: convertMinutesToHoursAndMinutes(vv.totalTimeMinute, true),
      isCrossDay: vv.overnightShift,
    })) as ScheduleScheme['shift'],
    team: (v.teamList || []).map((vv: any) => ({
      id: vv.id,
      name: vv.name,
    })),
    ...transformUser(v.schedulingScheme),
  }))
}

export function useScheduleSchemeLists() {
  const [loading, setLoading] = useState(true)
  const [lists, setLists] = useShallowState<
    ScheduleScheme[]
  >([])
  const columns: TableColumn<ScheduleScheme>[] = [
    { key: uuid(), label: '排班方案名称', prop: 'name' },
    {
      key: uuid(),
      label: '班次单元名称',
      prop: 'shiftUnit',
      render({ row }) {
        return h('span', row.shiftUnit.name)
      },
    },
    {
      key: uuid(),
      label: '班次',
      prop: 'shift',
      render({ row }) {
        return h(ScheduleSchemeShift, {
          data: row.shift,
        })
      },
    },
    {
      key: uuid(),
      label: '班组',
      prop: 'team',
      render({ row }) {
        return h(ScheduleSchemeTeam, {
          data: row.team,
        })
      },
    },
    {
      key: uuid(),
      label: '创建时间',
      prop: 'creationTime',
      hidden: true,
    },
    {
      key: uuid(),
      label: '创建人',
      prop: 'creatorUserName',
      render({ row }) {
        return h(
          'span',
          joinUser(
            row.creatorUserName,
            row.creatorLoginName,
          ),
        )
      },
    },
    {
      key: uuid(),
      label: '修改时间',
      prop: 'updateTime',
      hidden: true,
    },
    {
      key: uuid(),
      label: '修改人',
      prop: 'updatorUserName',
      hidden: true,
      render({ row }) {
        return h(
          'span',
          joinUser(
            row.updatorUserName,
            row.updatorLoginName,
          ),
        )
      },
    },
  ]
  const pagination = reactive({
    pageNumber: 1,
    pageSize: PAGE_SIZES[0]!,
    total: 0,
  })

  async function getLists(params: {
    schedulingSchemeName?: string
    shiftUnitName?: string
    teamName?: string
  }) {
    setLoading(true)
    try {
      const { data }
        = await schedulingApi.selectSchedulingSchemePage({
          pageNumber: pagination.pageNumber,
          pageSize: pagination.pageSize,
          ...params,
        })
      setLists(transfer(data.records || []))
      pagination.total = data.total
    }
    catch (e) {
    }
    finally {
      setLoading(false)
    }
  }

  return {
    loading,
    lists,
    columns,
    pagination,
    setLists,
    getLists,
    setLoading,
  }
}
